<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="addDialogVisible = true"
        >新增角色</el-button
      >
      <el-table :data="roleData" border style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', key1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, key1) in scope.row.permissions"
              :key="item1.id"
            >
              <el-col :span="5"
                ><el-tag closable @close="delRights(item1.id, scope.row)">{{
                  item1.title
                }}</el-tag>
                <i class="el-icon-caret-right"></i
              ></el-col>

              <el-col :span="19">
                <el-row
                  :class="[key2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, key2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6"
                    ><el-tag
                      type="success"
                      closable
                      @close="delRights(item2.id, scope.row)"
                      >{{ item2.title }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="delRights(item3.id, scope.row)"
                      >{{ item3.title }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="角色名称"> </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" type="success">开启</el-tag>

            <el-tag v-else-if="scope.row.status === 1" type="danger"
              >关闭</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="description" label="角色描述"> </el-table-column>
        <el-table-column prop="created_at" label="添加时间"> </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @open="getRightsList"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="addForm.status">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赋予权限节点" prop="permission_id">
          <el-tree
            :data="rightList"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="treeData"
            highlight-current
            :props="defaultProps"
            @check-change="handleCheckChange"
          >
          </el-tree>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @open="getRightsList"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赋予权限节点">
          <el-tree
            :data="rightList"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="treeData"
            highlight-current
            :props="defaultProps"
            @check-change="handleCheckChange"
          >
          </el-tree>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rightList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      // 该数组是选中的节点(半选的节点和全选的节点全都存储在这个数组)
      multipleSelection: [],
      // 该数组回显数据根据所对应的ID  进行默认勾选 (:default-checked-keys 这个) 和 (node-key="id") 这个两个并存
      resourceCheckedKey: [],
      roleData: [],
      total: 0,
      page: 1,
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 15
      },
      addDialogVisible: false,
      editDialogVisible: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            messgae: '角色名称的长度在2到10个字符之间',
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 6,
            max: 50,
            messgae: '角色名称的长度在6到50个字符之间',
            trigger: 'blur'
          }
        ],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
      },
      addForm: {
        name: '',
        description: '',
        status: 0,
        permissionIds: ''
      },
      editForm: {},
      editFormRules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            messgae: '角色名称的长度在2到10个字符之间',
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 6,
            max: 50,
            messgae: '角色名称的长度在6到50个字符之间',
            trigger: 'blur'
          }
        ],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    async getRoleList () {
      const { data: res } = await this.$http.get('api/admin/roles', {
        params: this.queryInfo
      })
      //   if (res.errno !== 0) {
      //     return this.$message.error('获取列表失败')
      //   }

      this.roleData = res.list
      this.total = res.total
      this.queryInfo.pageNum = res.page
    },
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getRoleList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getRoleList()
    },

    async getRightsList () {
      const { data: res } = await this.$http.get('api/permission/list')
      if (res.errno !== 0) {
        return this.$message.error('获取权限列表失败')
      }
      const data = res.data

      const arr = []
      //   for (let i = 0; i < data.length; i++) {
      //     arr.push({
      //       id: data[i]['id'],
      //       label: data[i]['title'],
      //       children: []
      //     })
      //     if (data[i].children) {
      //       for (let j = 0; j < data[i].children.length; j++) {
      //         arr[i].children.push({
      //           id: data[i]['children'][j]['id'],
      //           label: data[i]['children'][j]['title']
      //         })
      //       }
      //     }
      //   }

      this.rightList = res.data
    },
    addRoles () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'api/admin/roles',
          this.addForm
        )
        if (res.errno !== 0) {
          return this.$message.error(res.errmsg)
        }
        this.$message.success('添加权限成功')
        this.addDialogVisible = false
        this.getRoleList()
      })
    },

    //选中权限列表
    handleCheckChange () {
      //   let res = this.$refs.treeData.getCheckedNodes()
      //   console.log(this.$refs.treeData.getHalfCheckedKeys(), this.$refs.treeData.getCheckedKeys())

      let arr = []
      //   res.forEach(item => {
      //     arr.push(item.id)
      //   })
      //   let menuArr = this.unique(arr) // 去除重复的节点
      //   this.addForm.permissionIds = menuArr.join(',')
      //   this.editForm.permissionIds = menuArr.join(',')
      arr = this.$refs.treeData.getCheckedKeys().concat(this.$refs.treeData.getHalfCheckedKeys());
      console.log(arr)
      this.addForm.permissionIds = arr.join(',')
      this.editForm.permissionIds = arr.join(',')

    },
    // 数组去重
    unique (arr) {
      let newArr = []
      let len = arr.length
      for (let i = 0; i < len; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
          newArr.push(arr[i])
        }
      }
      return newArr
    },
    //编辑页面
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('api/admin/role?id=' + id)
      if (res.errno !== 0) {
        this.$message.error('获取数据失败')
      }
      this.editDialogVisible = true
      this.editForm = res.data
      let permissions = Object.values(res.data.permissions)
      this.$nextTick(function () {
        this.$refs.treeData.setCheckedKeys(permissions)
      })
    },
    //修改操作
    editRolesInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put('api/admin/roles', this.editForm)

        if (res.errno !== 0) {
          return this.$message.error('修改角色失败')
        }
        this.editDialogVisible = false
        this.getRoleList()
        this.$message.success('修改角色成功')

      })
    },
    //删除操作
    async delRole (id) {
      const res = await this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);

      if (res !== 'confirm') {
        return this.$message.info('取消删除操作');
      }
      const { data: res2 } = await this.$http.delete('api/admin/roles?id=' + id);
      if (res2.errno !== 0) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getRoleList()
    },

    async delRights (id, role) {
      const res = await this.$confirm(
        '此操作将永久解除该角色的权限,是否继续',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (res !== 'confirm') {
        return this.$message.info('取消删除操作')
      }
      const { data: res2 } = await this.$http.delete(
        'api/admin/role?id=' + id + '&role_id=' + role.id
      )
      if (res2.errno !== 0) {
        return this.$message.error(res2.errmsg)
      }
      this.$message.success('删除成功')
      //this.getRoleList()
      role.permissions = res2.data
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
